package com.mobartisan.workinglunch.ui.fragment;

import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.mobartisan.workinglunch.R;
import com.mobartisan.workinglunch.bean.AccountRecord;
import com.mobartisan.workinglunch.constants.Constants;
import com.mobartisan.workinglunch.ui.adapter.HistoryAdapter;
import com.mobartisan.workinglunch.ui.base.BaseFragment;
import com.mobartisan.workinglunch.util.SharedPreferencesUtil;
import com.mobartisan.workinglunch.util.ToastUtils;
import com.mobartisan.workinglunch.widget.swipRefreshLayout.SwipyRefreshLayout;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import rx.Subscriber;

import static com.mobartisan.workinglunch.ui.activity.LoginActivity.loge;

/**
 * Created by L on 2017/4/26.
 */

public class ListFragment extends BaseFragment implements SwipyRefreshLayout.OnRefreshListener, View.OnClickListener {

    public static final String TAG = ListFragment.class.getSimpleName();
    HistoryAdapter historyAdapter;
    @Bind(R.id.recyclerviewId)
    RecyclerView recyclerView;
    @Bind(R.id.SwipeRefreshId)
    SwipyRefreshLayout swipyRefreshLayout;
    List<AccountRecord> list = new ArrayList<>();
    boolean ispullup = false;
    boolean ispulldown = false;
    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    dataOption(Constants.TOP_REFRESH);
                    break;
            }
        }
    };
    @Bind(R.id.lin_default_page)
    LinearLayout linDefaultPage;


    private int pages = 0;


    private static ListFragment listFragment;

    public static ListFragment getFragmetntA() {
        if (listFragment == null) {
            listFragment = new ListFragment();
        }
        return listFragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_list;
    }

    @Override
    protected void initView(View view) {
        TextView title = (TextView) view.findViewById(R.id.common_title_title);
        title.setText("历史记录");
    }

    @Override
    protected void initData() {

        historyAdapter = new HistoryAdapter(list);
        recyclerView.setAdapter(historyAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        swipyRefreshLayout.setOnRefreshListener(this);
        linDefaultPage.setOnClickListener(this);
        //initData(pages);
        queryObjects(0);
    }

    @Override
    public void onRefresh(int index) {
        dataOption(Constants.TOP_REFRESH);
    }

    @Override
    public void onLoad(int index) {
        dataOption(Constants.BOTTOM_REFRESH);

    }

    public void dataOption(int option) {
        switch (option) {
            case Constants.TOP_REFRESH:
                //下拉刷新
                ispullup = true;
                pages = 0;
                queryObjects(0);
                break;
            case Constants.BOTTOM_REFRESH:
                //上拉加载更多
                pages += 10;
                queryObjects(pages);
                break;
        }
    }

    public void queryObjects(int pages) {
        String userId = SharedPreferencesUtil.getInstance().getStringValue("username");
        final BmobQuery<AccountRecord> bmobQuery = new BmobQuery<AccountRecord>();
        bmobQuery.addWhereEqualTo("userId", userId);
        bmobQuery.order("-dateStamp,-timeStamp");
        bmobQuery.setSkip(pages);
        bmobQuery.setLimit(10);

        //bmobQuery.setLimit(2);
//        bmobQuery.order("createdAt");
//        //先判断是否有缓存
//        boolean isCache = bmobQuery.hasCachedResult(AccountRecord.class);
//        if(isCache){
//            bmobQuery.setCachePolicy(BmobQuery.CachePolicy.CACHE_ELSE_NETWORK);	// 先从缓存取数据，如果没有的话，再从网络取。
//        }else{
//            bmobQuery.setCachePolicy(BmobQuery.CachePolicy.NETWORK_ELSE_CACHE);	// 如果没有缓存的话，则先从网络中取
//        }
//		observable形式
        bmobQuery.findObjectsObservable(AccountRecord.class)
                .subscribe(new Subscriber<List<AccountRecord>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        loge(e,TAG);
                        if (((BmobException) e).getErrorCode() == Constants.Network_Error_Code) {
                            ToastUtils.showShort("请检查您的网络");
                        } else if (((BmobException) e).getErrorCode() == Constants.Network_Timeout_Code) {
                            ToastUtils.showShort("网络超时");
                        }
                        swipyRefreshLayout.setVisibility(View.GONE);
                        recyclerView.setVisibility(View.GONE);
                        linDefaultPage.setVisibility(View.VISIBLE);
                        swipyRefreshLayout.setRefreshing(false);
                    }

                    @Override
                    public void onNext(List<AccountRecord> persons) {
                        //log("查询成功：共"+persons.size()+"条数据。");
                        //ToastUtils.showShort("查询成功：共" + persons.size() + "条数据。");
                        //给数据重新排序
                        if (ispullup) {
                            list.clear();
                        }
                        if (10 > persons.size()&&!ispulldown) {
                                ToastUtils.showShort("已加载全部数据");
                        }
                        if (persons.size()==0&&ispulldown){
                            ToastUtils.showShort("暂无数据");
                        }
                        ispulldown = false;
                        ispullup = false;
                        //Collections.sort(persons,comparator);

                        list.addAll(persons);
                        if (list.size() == 0) {
                            swipyRefreshLayout.setVisibility(View.GONE);
                            recyclerView.setVisibility(View.GONE);
                            linDefaultPage.setVisibility(View.VISIBLE);
                        } else {
                            swipyRefreshLayout.setVisibility(View.VISIBLE);
                            recyclerView.setVisibility(View.VISIBLE);
                            linDefaultPage.setVisibility(View.GONE);
                        }
                        historyAdapter.notifyDataSetChanged();
                        swipyRefreshLayout.setRefreshing(false);
                    }
                });
//		bmobQuery.findObjects(new FindListener<Person>() {
//
//			@Override
//			public void done(List<Person> object, BmobException e) {
//				if(e==null){
//					toast("查询成功：共"+object.size()+"条数据。");
//					for (Person person : object) {
//						Log.d(TAG, "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ");
//						Log.d(TAG, "ObjectId = "+person.getObjectId());
//						Log.d(TAG, "Name = "+person.getName());
//						Log.d(TAG, "Age = "+person.getAge());
//						Log.d(TAG, "Address = "+person.getAddress());
//						Log.d(TAG, "Gender = "+person.isGender());
//						Log.d(TAG, "CreatedAt = "+person.getCreatedAt());
//						Log.d(TAG, "UpdatedAt = "+person.getUpdatedAt());
//					}
//				}else{
//					loge(e);
//				}
//			}
//		});
    }

    Comparator<AccountRecord> comparator = new Comparator<AccountRecord>() {
        public int compare(AccountRecord s1, AccountRecord s2) {
            //先排日期
            String judgedate, judgedate2, judgetime, judgetime2;
            judgedate = s1.getDateStamp();
            judgedate = judgedate.replace("-", "");
            int datenomber = Integer.parseInt(judgedate);
            judgedate2 = s2.getDateStamp();
            judgedate2 = judgedate2.replace("-", "");
            int datenomber2 = Integer.parseInt(judgedate2);

            judgetime = s1.getTimeStamp();
            judgetime = judgetime.replace(":", "");
            int timenomber = Integer.parseInt(judgetime);
            judgetime2 = s2.getTimeStamp();
            judgetime2 = judgetime2.replace(":", "");
            int timenomber2 = Integer.parseInt(judgetime2);
            if (datenomber != datenomber2) {
                return datenomber - datenomber2;
            } else {
                //日期相同则按时间排序

                if (timenomber != timenomber2) {
                    return timenomber - timenomber2;
                } else {
                    //时间也相同则按金钱排序
                    return (int) (s1.getMoney() - s2.getMoney());
                }


            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        list.clear();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lin_default_page:
                dataOption(Constants.TOP_REFRESH);
                ispulldown = true;
                break;
        }
    }
}
